package com.example.admin.kline;

import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;

import com.example.admin.kline.entry.KMAEntity;
import com.github.mikephil.charting.charts.CombinedChart;
import com.github.mikephil.charting.components.Description;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.CandleData;
import com.github.mikephil.charting.data.CandleDataSet;
import com.github.mikephil.charting.data.CandleEntry;
import com.github.mikephil.charting.data.CombinedData;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ViewPortHandler;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {
    private CombinedChart chart;
    private List<CandleEntry> candleEntries;
    private ArrayList<String> xVals;
    private int itemCount;
    private int colorMa5 = Color.BLUE;
    private int colorMa10 = Color.CYAN;
    private int colorMa20 = Color.GRAY;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initData();
    }



    private void initData() {
        List<StockListBean.StockBean> stockBeans = Model.getData();
        xVals = new ArrayList<>();
        candleEntries = new ArrayList<>();
        for (int i = 0; i < stockBeans.size(); i++) {
            StockListBean.StockBean bean = stockBeans.get(i);
            candleEntries.add(new CandleEntry(i, bean.getHigh(), bean.getLow(), bean.getOpen(), bean.getClose()));
            xVals.add(bean.getDate());
        }

        CandleDataSet set = new CandleDataSet(candleEntries, "Data Set");
        set.setAxisDependency(YAxis.AxisDependency.LEFT);
        set.setShadowColor(Color.DKGRAY);//影线颜色
        set.setShadowColorSameAsCandle(true);//影线颜色与实体一致
        set.setShadowWidth(0.7f);//影线
        set.setDecreasingColor(Color.RED);//涨
        set.setDecreasingPaintStyle(Paint.Style.FILL);//红涨，实体
        set.setIncreasingColor(Color.GREEN);//跌
        set.setIncreasingPaintStyle(Paint.Style.STROKE);//绿跌，空心
        set.setNeutralColor(Color.RED);//当天价格不涨不跌（一字线）颜色
        set.setHighlightLineWidth(1f);//选中蜡烛时的线宽
        set.setDrawValues(false);//在图表中的元素上面是否显示数值
        set.setLabel("label");//图表名称，可以通过mChart.getLegend().setEnable(true)显示在标注上
        CandleData candleData = new CandleData(set);

        ArrayList<Entry> ma5DataL = new ArrayList<>();
        ArrayList<Entry> ma10DataL = new ArrayList<>();
        ArrayList<Entry> ma20DataL = new ArrayList<>();

        KMAEntity kmaEntity5 = new KMAEntity(stockBeans, 5);
        KMAEntity kmaEntity10 = new KMAEntity(stockBeans, 10);
        KMAEntity kmaEntity15 = new KMAEntity(stockBeans, 15);

        for (int i = 0; i < kmaEntity5.getMAs().size(); i++) {
            ma5DataL.add(new Entry(i,kmaEntity5.getMAs().get(i)));
            ma10DataL.add(new Entry(i,kmaEntity10.getMAs().get(i)));
            ma20DataL.add(new Entry(i, kmaEntity15.getMAs().get(i)));
        }

        ArrayList<ILineDataSet> sets = new ArrayList<>();
        /******此处修复如果显示的点的个数达不到MA均线的位置所有的点都从0开始计算最小值的问题******************************/
        sets.add(setMaLine(5, xVals, ma5DataL));
        sets.add(setMaLine(10, xVals, ma10DataL));
        sets.add(setMaLine(15, xVals, ma20DataL));

        LineData lineData = new LineData(sets);

        CombinedData combinedData = new CombinedData();
        combinedData.setData(candleData);
        combinedData.setData(lineData);
        initChartKline();
        chart.setDrawOrder(new CombinedChart.DrawOrder[]{CombinedChart.DrawOrder.CANDLE, CombinedChart.DrawOrder.LINE});
        chart.setData(combinedData);
        chart.setAutoScaleMinMaxEnabled(true);
        chart.notifyDataSetChanged();
        chart.moveViewToX(xVals.size() - 1);
        chart.invalidate();
    }

    @NonNull
    private LineDataSet setMaLine(int ma, ArrayList<String> xVals, ArrayList<Entry> lineEntries) {
        LineDataSet lineDataSetMa = new LineDataSet(lineEntries, "ma" + ma);
        if (ma == 5) {
            lineDataSetMa.setHighlightEnabled(true);
            lineDataSetMa.setDrawHorizontalHighlightIndicator(false);
            lineDataSetMa.setHighLightColor(getResources().getColor(R.color.marker_line_bg));
        } else {/*此处必须得写*/
            lineDataSetMa.setHighlightEnabled(false);
        }
        lineDataSetMa.setDrawValues(false);
        if (ma == 5) {
            lineDataSetMa.setColor(getResources().getColor(R.color.ma5));
        } else if (ma == 10) {
            lineDataSetMa.setColor(getResources().getColor(R.color.ma10));
        } else if (ma == 20) {
            lineDataSetMa.setColor(getResources().getColor(R.color.ma20));
        } else {
            lineDataSetMa.setColor(getResources().getColor(R.color.ma30));
        }
        lineDataSetMa.setLineWidth(1f);
        lineDataSetMa.setDrawCircles(false);
        lineDataSetMa.setAxisDependency(YAxis.AxisDependency.LEFT);
        lineDataSetMa.setHighlightEnabled(false);
        return lineDataSetMa;
    }


    /**
     * 初始化chart公共属性
     */
    private void initChartKline() {
        chart=findViewById(R.id.chart);
        chart.setDragEnabled(true);//启用图表拖拽事件
        chart.setScaleEnabled(true);//启用图表缩放事件
        chart.setScaleYEnabled(false);//启用Y轴上的缩放
        chart.setDrawBorders(true);//是否绘制边线
        chart.setBorderWidth(1);//边线宽度，单位dp
        chart.setBorderColor(getResources().getColor(R.color.border_color));//边线颜色
        Description description=new Description();
        description.setEnabled(false);
        chart.setDescription(description);//右下角对图表的描述信息
        chart.setMinOffset(0f);
        chart.setExtraOffsets(0f, 0f, 0f, 3f);
        chart.fitScreen();
        chart.setPinchZoom(false);
        Legend lineChartLegend = chart.getLegend();
        lineChartLegend.setEnabled(false);//是否绘制 Legend 图例
        lineChartLegend.setForm(Legend.LegendForm.CIRCLE);

        //bar x y轴
        XAxis xAxisKline = chart.getXAxis();
        xAxisKline.setDrawLabels(true); //是否显示X坐标轴上的刻度，默认是true
        xAxisKline.setDrawGridLines(false);//是否显示X坐标轴上的刻度竖线，默认是true
        xAxisKline.setDrawAxisLine(false); //是否绘制坐标轴的线，即含有坐标的那条线，默认是true
        xAxisKline.enableGridDashedLine(10f, 10f, 0f);//虚线表示X轴上的刻度竖线(float lineLength, float spaceLength, float phase)三个参数，1.线长，2.虚线间距，3.虚线开始坐标
        xAxisKline.setTextColor(getResources().getColor(R.color.colorText));//设置字的颜色
        xAxisKline.setPosition(XAxis.XAxisPosition.BOTTOM);//设置值显示在什么位置
        xAxisKline.setAvoidFirstLastClipping(true);//设置首尾的值是否自动调整，避免被遮挡
        xAxisKline.setValueFormatter(new DateFormatter(xVals));
        xAxisKline.setLabelCount(3,false);

        YAxis axisLeftKline = chart.getAxisLeft();
        axisLeftKline.setDrawGridLines(true);
        axisLeftKline.setDrawAxisLine(false);
        axisLeftKline.setDrawZeroLine(false);
        axisLeftKline.setDrawLabels(true);
        axisLeftKline.enableGridDashedLine(10f, 10f, 0f);
        axisLeftKline.setTextColor(getResources().getColor(R.color.colorText));
//        axisLeftKline.setGridColor(getResources().getColor(R.color.minute_grayLine));
        axisLeftKline.setPosition(YAxis.YAxisLabelPosition.INSIDE_CHART);
        axisLeftKline.setLabelCount(10, false); //第一个参数是Y轴坐标的个数，第二个参数是 是否不均匀分布，true是不均匀分布
        axisLeftKline.setSpaceTop(10);//距离顶部留白
        axisLeftKline.setSpaceBottom(10);



        YAxis axisRightKline = chart.getAxisRight();
        axisRightKline.setDrawLabels(false);
        axisRightKline.setDrawGridLines(false);
        axisRightKline.setDrawAxisLine(false);
        axisRightKline.setLabelCount(4, false); //第一个参数是Y轴坐标的个数，第二个参数是 是否不均匀分布，true是不均匀分布
        axisRightKline.setEnabled(false);

        chart.setDragDecelerationEnabled(true);
        chart.setDragDecelerationFrictionCoef(0.2f);
        chart.animateXY(2000, 2000);
    }

    private float culcMaxscale(float count) {
        float max = 1;
        max = count / 127 * 5;
        return max;
    }


}
